<template>
  <div class="app-container">
    <!-- 上表格 -->
    <el-table :data="exchangeRateApiList">
      <el-table-column label="来源名称" prop="apiName" />
      <el-table-column label="更新时间" align="center" prop="newLastModified" />
      <el-table-column label="优先级" align="center" prop="priority" />
      <el-table-column label="状态" align="center" prop="newStatus" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="handleUpdate(scope.row)"
            v-hasPermi="['productSto:managedExchangeRate:edit']"
            >测试</el-button
          >
          <el-button
            type="primary"
            link
            @click="handleExchangeRateEdit(scope.row)"
            v-hasPermi="['productSto:managedExchangeRate:remove']"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 下表格 ---------------⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️------------------>
    <div>
      <p style="font-weight: bold; font-size: 20px">常用汇率</p>
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleAdjustmentEntry"
        >调整记录</el-button
      >
      <el-text size="large" style="margin-left: 10px"
        >汇率以1美元为基准计算</el-text
      >
    </div>

    <el-table :data="exchangeRatesList">
      <el-table-column label="货币" align="center" prop="description" />
      <el-table-column label="货币代码" align="center" prop="code" />
      <el-table-column label="汇率" align="center" prop="rate" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="newTime"
        width="180"
      />

      <el-table-column label="是否锁定">
        <template #default="scope">
          <el-space spacer=" ">
            {{ scope.row.newLockStatus }}
            <el-button
              @click="unlockBtn(scope.row)"
              plain
              v-if="scope.row.lockStatus"
              >解锁</el-button
            >
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="seq" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleManualSetting(scope.row)"
            >手动调整</el-button
          >
          <el-button
            type="danger"
            link
            @click="handleDelete(scope.row)"
            v-if="!scope.row.lockStatus"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      :limit="searchParams.pageSize"
      :page="searchParams.pageNum"
      @pagination="handlePageChange"
    ></Pagination>
    <dialogCommonly
      :item="publicFrom"
      :newUsualRatesVisible="newUsualRatesVisible"
      @handleFormSubmit="handleFormSubmit"
      @newUsualRatesCancel="newUsualRatesCancel"
    ></dialogCommonly>

    <el-dialog
      title="汇率API编辑"
      v-model="exchangeRateEditVisible"
      width="600px"
    >
      <el-form
        :rules="exchangeRateEditFormRules"
        :model="exchangeRateForm"
        ref="exchangeRateFormRef"
        label-width="100px"
      >
        <el-form-item label="来源名称" prop="apiName">
          {{ publicFrom.apiName }}
        </el-form-item>
        <el-form-item label="来源网站" prop="apiUrl">
          {{ publicFrom.apiUrl }}
        </el-form-item>
        <el-form-item label="AccessKey" prop="accessKey">
          <el-input
            v-model.trim="exchangeRateForm.accessKey"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="AppSecret" prop="appSecret">
          <el-input
            v-model.trim="exchangeRateForm.appSecret"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input
            v-model.trim="exchangeRateForm.priority"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="exchangeRateEditCancel">取 消</el-button>
          <el-button type="primary" @click="exchangeRateEditFormSubmit"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
    <adjustMent
      :publicFrom="publicFrom"
      :manualSettingVisible="manualSettingVisible"
      @manualSettingFormCancel="manualSettingFormCancel"
      @manualSettingFormSubmit="manualSettingFormSubmit"
    ></adjustMent>

    <el-dialog title="调整记录" v-model="adjustmentEntryVisible" width="60%">
      <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
        <el-form
          :model="searchParams.param"
          ref="queryParamsRef"
          :inline="true"
        >
          <el-form-item label="货币代码" prop="code">
            <el-input
              v-model.trim="searchParams.param.code"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="调整时间" prop="settlingTime">
            <el-date-picker
              v-model="searchParams.param.settlingTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="解锁时间" prop="unlockTime">
            <el-date-picker
              v-model="searchParams.param.unlockTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </searchBox>

      <el-table :data="tableData" height="500">
        <el-table-column prop="code" label="货币代码" align="center" />
        <el-table-column prop="rate" label="汇率值" align="center" />
        <el-table-column prop="newCreated" label="调整时间" align="center" />
        <el-table-column prop="unlockTime" label="解锁时间" align="center" />
        <el-table-column
          prop="practiceTime"
          label="实际解锁时间"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.status ? scope.row.practiceTime : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="调整原因" />
      </el-table>
      <Pagination
        :total="recordTotal"
        :limit="searchParams.pageSize"
        :page="searchParams.pageNum"
        @pagination="handleCurrentChange"
      ></Pagination>
    </el-dialog>
  </div>
</template>

<script setup >
import { reactive, ref, onMounted } from "vue";
import dialogCommonly from "./component/dialog.vue";
import adjustMent from "./component/adjustment.vue";

const { proxy } = getCurrentInstance();
const publicFrom = ref({}); //公共赋值对象

const manuaDataList = ref({}); // 手动调整头部数据
const tableData = ref([]); // 调整记录表格数据
const sys_currency_code = ref([]); //货币

// 调整记录查询参数
const searchParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    code: "", //货币编码
    startTime: "", //调整开始时间
    endTime: "", //调整结束时间
    unlockStartTime: "", //解锁开始时间
    unlockEndTime: "", //解锁结束时间
  },
});

// 调整记录弹框
const adjustmentEntryVisible = ref(false);
const recordTotal = ref(1); //调整记录总数
// 手动调整弹框表单参数
const manualSettingForm = ref({});
const manualSettingVisible = ref(false);
// 新增常用汇率弹框参数
const newUsualRatesForm = ref({
  code: null,
  seq: 0,
});
const exchangeRateEditFormRules = ref({
  accessKey: [
    { required: true, message: "请输入AccessKey", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "请正确输入AccessKey",
      trigger: "blur",
    },
  ],
  appSecret: [
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "请正确输入AppSecret",
      trigger: "blur",
    },
  ],
  priority: [
    { required: true, message: "请输入优先级", trigger: "blur" },
    {
      pattern: /^(0|[1-9]\d*)$/,
      message: "只能输入整数",
      trigger: "blur",
    },
  ],
});
const formRules = ref({});
// 控制新增常用汇率弹框
const newUsualRatesVisible = ref(false);
// 汇率api弹框控制
const exchangeRateEditVisible = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);

// 总条数
const total = ref(0);
// 常用货币汇率表格数据
const exchangeRatesList = ref([]);
// 汇率api表格数据
const exchangeRateApiList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 表单参数
const form = ref({});
// 汇率api表单参数
const exchangeRateForm = ref({});

onMounted(() => {
  getList();
  getExchangeRateApiList();
  getLanguage();
});

const dialogResetForm = () => {
  searchParams.value = {
    pageNum: 1,
    pageSize: 10,
    param: {},
  };
};
// 分页设置选项
const handleCurrentChange = (val) => {
  searchParams.value.pageNum = val.page;
  searchParams.value.pageSize = val.limit;
  getAdjustRecordList();
};
// 调整记录列表
const getAdjustRecordList = () => {
  rate.exchangerate
    .exchangerateAdjustrecordlist({
      data: searchParams.value,
    })
    .then((response) => {
      if (response.data.length) {
        response.data = response.data.map((code) => {
          return {
            ...code,
            newCreated: proxy.DateTime(code.created),
            unlockTime: proxy.DateTime(code.endTime),
            practiceTime: proxy.DateTime(code.lastModified),
          };
        });
      }
      tableData.value = response.data;
      recordTotal.value = response.total;
    });
};
// 手动调整按钮操作
const handleManualSetting = (e) => {
  manualSettingVisible.value = true;
  publicFrom.value = e;
};
// 手动调整取消
const manualSettingFormCancel = () => {
  manualSettingVisible.value = false;
  publicFrom.value = {};
};
// 手动调整提交
const manualSettingFormSubmit = () => {
  manualSettingVisible.value = false;
  getList();
  getExchangeRateApiList();
  getLanguage();
};
// 汇率api编辑按钮操作
const handleExchangeRateEdit = (e) => {
  publicFrom.value = e;
  exchangeRateForm.value.accessKey = e.accessKey;
  exchangeRateForm.value.appSecret = e.appSecret;
  exchangeRateForm.value.id = e.id;
  exchangeRateForm.value.priority = e.priority;
  exchangeRateEditVisible.value = true;
};
// api编辑取消按钮操作
const exchangeRateEditCancel = () => {
  exchangeRateEditVisible.value = false;
  resetExchangeRateForm();
};
// api编辑提交按钮操作
const exchangeRateEditFormSubmit = () => {
  proxy.$refs["exchangeRateFormRef"].validate((valid) => {
    if (valid) {
      // console.log(exchangeRateForm.value);
      // return
      rate.exchangerate
        .exchangerateEditapi({
          data: exchangeRateForm.value,
        })
        .then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          exchangeRateEditVisible.value = false;
          resetExchangeRateForm();
        });
    }
  });
};
// 新增汇率取消按钮操作
const newUsualRatesCancel = () => {
  newUsualRatesVisible.value = false;
  publicFrom.value = {};
};
// 新增汇率提交按钮操作
const handleFormSubmit = (formEl) => {
  newUsualRatesVisible.value = false;
  getList();
  getExchangeRateApiList();
  getLanguage();
};
/** 查询汇率api列表 */
const getExchangeRateApiList = () => {
  rate.exchangerate
    .exchangerateExchangerateapilist({
      data: {
        pageNum: 1,
        pageSize: 10,
        param: {},
      },
    })
    .then((response) => {
      if (response.data.length) {
        response.data = response.data.map((code) => {
          return {
            ...code,
            newLastModified: proxy.DateTime(code.lastModified),
            newStatus: code.status ? "正常" : "失败",
          };
        });
      }
      exchangeRateApiList.value = response.data;
    });
};
const handlePageChange = (newPage) => {
  searchParams.value.pageSize = newPage.page;
  searchParams.value.pageNum = newPage.limit;
  getList();
};

//   查询常用货币汇率列表
const getList = () => {
  rate.exchangerate
    .exchangerateCommonlyusedexchangeratelist({
      data: searchParams.value,
    })
    .then((response) => {
      if (response.data.length) {
        response.data = response.data.map((code) => {
          return {
            ...code,
            newTime: proxy.DateTime(code.updateTime),
            newLockStatus: code.lockStatus ? "是" : "否",
          };
        });
      }

      exchangeRatesList.value = response.data;
      total.value = response.total;
    });
};
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};
// 新增常用汇率参数重置
const resetNewUsualRatesForm = () => {
  newUsualRatesForm.value = {
    code: "",
    seq: null,
  };
  getList();
};
// 汇率API编辑参数重置
const resetExchangeRateForm = () => {
  exchangeRateForm.value = {
    accessKey: "",
    appSecret: "",
    id: null,
    priority: null,
  };
  getExchangeRateApiList();
};
// 表单重置
const reset = () => {
  form.value = {
    id: null,
    productId: null,
    langType: null,
    name: null,
    description: null,
    title: null,
    tagDescription: null,
    tagKeywords: null,
    tags: null,
    deleted: null,
    created: null,
    lastModified: null,
  };
  proxy.resetForm("form");
};
// 调整记录按钮
const handleAdjustmentEntry = () => {
  resetQuery();
  adjustmentEntryVisible.value = true;
  getAdjustRecordList();
  // this.searchParams = {}
};

/** 搜索按钮操作 */
const handleQuery = () => {
  // 调整开始时间
  if (searchParams.value.param.settlingTime) {
    console.log(searchParams.value.param.settlingTime);

    searchParams.value.param.startTime = proxy.convertTime(
      1,
      searchParams.value.param.settlingTime[0]
    );
    searchParams.value.param.endTime = proxy.convertTime(
      1,
      searchParams.value.param.settlingTime[1]
    );
  }
  // 解锁开始时间
  if (searchParams.value.param.unlockTime) {
    searchParams.value.param.unlockStartTime = proxy.convertTime(
      1,
      searchParams.value.param.unlockTime[0]
    );
    searchParams.value.param.unlockEndTime = proxy.convertTime(
      1,
      searchParams.value.param.unlockTime[1]
    );
  }
  // console.log(searchParams.value, "搜索按钮操作");
  getAdjustRecordList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  searchParams.value.param = {};
  proxy.resetForm("queryParamsRef");
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  publicFrom.value = {};
  newUsualRatesVisible.value = true;
  console.log(newUsualRatesVisible.value, "新增按钮操作");
};
/** 测试按钮操作 */
const handleUpdate = (row) => {
  rate.exchangerate
    .exchangerateTestapi({
      data: {
        apiName: row.apiName,
      },
    })
    .then((response) => {
      if (response.code === 200) {
        reset();
        proxy.$modal.msgSuccess(response.message);
        getExchangeRateApiList();
      }
    })
    .catch((error) => {
      reset();
      proxy.$modal.msgError("测试失败");
    });
};

// 解锁按钮操作
const unlockBtn = (e) => {
  proxy.$modal
    .confirm("是否确认解锁当前汇率的数据项？")
    .then(() => {
      rate.exchangerate
        .exchangerateUnlock({
          data: {
            id: e.id,
          },
        })
        .then((response) => {
          proxy.$modal.msgSuccess("解锁成功");
          getList();
        });
    })
    .catch(() => {});
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  const ids = row.id || ids;
  proxy.$modal
    .confirm("是否确认删除当前汇率的数据项？")
    .then(function () {
      return rate.exchangerate.exchangerateDeletecommonlyusedcurrency({
        data: { id: ids },
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
const getLanguage = () => {
  // 获取货币
  product.currency.currencyList().then((res) => {
    sys_currency_code.value = res.data;
  });
};
</script>
<style>
.manualSettingFormstyle {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
}

.manualSettingFormstyleLeftContainer {
  margin-right: 50px;
}

.manualSettingFormstyleLeft {
  display: flex;
  align-items: center;
}

.manualSettingFormstyleRight {
  display: flex;
  align-items: center;
}
</style>
